package com.wl.video.live.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.TextHttpResponseHandler;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;
import com.wl.video.live.AppContext;
import com.wl.video.live.R;
import com.wl.video.live.api.LiveAPI;
import com.wl.video.live.entity.LiveVideoEntity;
import com.wl.video.live.utils.TimeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class VideoActivity extends Activity {

    @Bind(R.id.live_video_list)
    UltimateRecyclerView live_video_list;

    LiveVideoApdapter liveVideoApdapter;

    ClipboardManager mClipboardManager;


    private List<LiveVideoEntity> mData = new ArrayList<LiveVideoEntity>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        ButterKnife.bind(this);

//        for (int i=1;i<10;i++){
//
//            LiveVideoEntity liveVideoEntity = new LiveVideoEntity();
//            liveVideoEntity.setId("11");
//            liveVideoEntity.setCreateTime("2019-01-17 11:29");
//            liveVideoEntity.setSeePeopliNum("12");
//            liveVideoEntity.setLabel("梦妹身上驰骋"+i);
//            mData.add(liveVideoEntity);
//        }

        liveVideoApdapter = new LiveVideoApdapter(this, mData);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        live_video_list.setLayoutManager(layoutManager);
        live_video_list.setAdapter(liveVideoApdapter);
        live_video_list.disableLoadmore();
        mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

        String deviceId = AppContext.getInstance().getAppId();
        LiveAPI.getLiveVideo(deviceId, channelHandler);
    }

    private final TextHttpResponseHandler channelHandler = new TextHttpResponseHandler() {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Toast.makeText(getApplication(), "获取录像信息失败，请重新尝试！", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            //获取直播推流地址，频道号，考虑记录在本地
            if (statusCode == 200) {
                StringBuilder builder = new StringBuilder();
                builder.append(responseString);
                String builder_BOM = jsonTokener(builder.toString());
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject = JSONObject.parseObject(builder_BOM);
                    String code = jsonObject.getString("success");
                    if (code.trim().equals("true")) {
                        String body = jsonObject.getString("data");
                        jsonObject = JSONObject.parseObject(body);
                        body = jsonObject.getString("videoList");
                        List<LiveVideoEntity> templist = JSON.parseArray(body,
                                LiveVideoEntity.class);

                        //刷新列表
                        if (templist.size() > 0) {
                            for (int i = 0; i < templist.size(); i++) {
                                liveVideoApdapter.insert(templist.get(i), liveVideoApdapter.getAdapterItemCount());
                            }

                            live_video_list.scrollVerticallyToPosition(0);
                            liveVideoApdapter.notifyDataSetChanged();
                            live_video_list.disableLoadmore();
                        }
                    } else {
                        live_video_list.disableLoadmore();
                    }

                } catch (Exception e) {
                    Toast.makeText(getApplication(), "获取录像信息失败，请重新尝试！", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getApplication(), "获取录像信息失败，请重新尝试！", Toast.LENGTH_LONG).show();
            }
        }
    };

    private final TextHttpResponseHandler labelHandler = new TextHttpResponseHandler() {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Toast.makeText(getApplication(), "更改录像标签失败！", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            //获取直播推流地址，频道号，考虑记录在本地
            if (statusCode == 200) {
                StringBuilder builder = new StringBuilder();
                builder.append(responseString);
                String builder_BOM = jsonTokener(builder.toString());
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject = JSONObject.parseObject(builder_BOM);
                    String code = jsonObject.getString("success");
                    if (code.trim().equals("true")) {
                        Toast.makeText(getApplication(), "更改录像标签成功！", Toast.LENGTH_LONG).show();

                        initData();
                    } else {
                        Toast.makeText(getApplication(), "更改录像标签失败！", Toast.LENGTH_LONG).show();
                    }

                } catch (Exception e) {
                    Toast.makeText(getApplication(), "更改录像标签失败！", Toast.LENGTH_LONG).show();
                }
            } else {

            }
        }
    };

    @OnClick(R.id.iv_back)
    protected void back() {
//        Intent intent = new Intent(ShowActivity.this, MainActivity.class);
//        startActivity(intent);
        finish();
    }

    public void initData() {
        liveVideoApdapter.clear();
        String deviceId = AppContext.getInstance().getAppId();
        LiveAPI.getLiveVideo(deviceId, channelHandler);
    }

    protected String jsonTokener(String in) {
        if (in != null && in.startsWith("\ufeff")) {
            in = in.substring(1);
        }
        return in;
    }


    class LiveVideoApdapter extends UltimateViewAdapter<ViewHolder> {

        private Context context;
        private List<LiveVideoEntity> stringList;
        private int curposition;


        public LiveVideoApdapter(Context context, List<LiveVideoEntity> stringList) {
            this.context = context;
            this.stringList = stringList;
        }

        @Override
        public ViewHolder newFooterHolder(View view) {
            return null;
        }

        @Override
        public ViewHolder newHeaderHolder(View view) {
            return null;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.video_item, parent, false);
            ViewHolder vh = new ViewHolder(v, true);
            return vh;
        }

        @Override
        public int getAdapterItemCount() {
            return stringList.size();
        }

        public void insert(LiveVideoEntity localShopVisit, int position) {
            insertInternal(stringList, localShopVisit, position);
        }

        public void clear() {
            stringList.clear();
            this.notifyDataSetChanged();
        }

        @Override
        public long generateHeaderId(int position) {
            return 0;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            if (position < getItemCount() && (customHeaderView != null ? position <= stringList.size() : position < stringList.size()) && (customHeaderView != null ? position > 0 : true)) {
                //初始化
                final LiveVideoEntity lue = getItem(position);
                if (lue != null) {
//                    ((ViewHolder) holder).video_time_item.setText(lue.getCreateTime());
                    ((ViewHolder) holder).video_time_item.setText(TimeUtils.getTime(Long.valueOf(lue.getCreateTime()),TimeUtils.DEFAULT_DATE_FORMAT));
                    ((ViewHolder) holder).video_num_item.setText(lue.getSeePeopliNum());
                    ((ViewHolder) holder).video_tag_item.setText(lue.getLabel() == null ? "添加标签" : lue.getLabel());
                    holder.video_tag_item.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            final EditText editText = new EditText(context);
                            editText.setText(lue.getLabel());
                            InputFilter[] filters = {new InputFilter.LengthFilter(10)};
                            editText.setFilters(filters);
//                                editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                            new AlertDialog.Builder(context)
                                    .setTitle("请输入标签")
                                    .setIcon(R.mipmap.ic_launcher)
                                    .setView(editText)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (null != editText.getText() && editText.getText().toString().trim() != "") {
                                                LiveAPI.updateVideoTag(lue.getId(), editText.getText().toString(), labelHandler);
                                            }
                                            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                                            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                                            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                                        }
                                    })
                                    .show();
                        }
                    });
                    holder.video_play_item.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AlertDialog alertDialog1 = new AlertDialog.Builder(context)
                                    .setTitle("复制播放链接")//标题
                                    .setMessage(lue.getLiveUrl())//内容
                                    .setIcon(R.mipmap.ic_launcher)
                                    .setPositiveButton("复制", new DialogInterface.OnClickListener() {//添加普通按钮
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            String copyValue = "观看地址:" + lue.getLiveUrl();
                                            ClipData clipData = ClipData.newPlainText("copy from demo", copyValue);
                                            mClipboardManager.setPrimaryClip(clipData);
                                            Toast.makeText(getApplication(), "录像观看地址复制成功！", Toast.LENGTH_LONG).show();
                                        }
                                    })
                                    .create();
                            alertDialog1.show();
                        }
                    });


                }
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
            return null;
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position) {

        }

        public LiveVideoEntity getItem(int position) {
            if (customHeaderView != null)
                position--;
            if (position < stringList.size())
                return stringList.get(position);
            else return null;
        }


    }

    class ViewHolder extends UltimateRecyclerviewViewHolder {
        public TextView video_time_item;
        public TextView video_num_item;
        public TextView video_tag_item;
        public ImageView video_play_item;

        public RelativeLayout id_video_item;

        public ViewHolder(View itemView, boolean isItem) {
            super(itemView);
            if (isItem) {
                video_time_item = (TextView) itemView.findViewById(R.id.video_time_item);
                video_num_item = (TextView) itemView.findViewById(R.id.video_num_item);
                video_tag_item = (TextView) itemView.findViewById(R.id.video_tag_item);
                video_play_item = (ImageView) itemView.findViewById(R.id.video_play_item);
                video_tag_item.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                id_video_item = (RelativeLayout) itemView.findViewById(R.id.id_video_item);
            }
        }

        @Override
        public void onItemSelected() {
            itemView.setBackgroundColor(Color.LTGRAY);
        }

        @Override
        public void onItemClear() {
            itemView.setBackgroundColor(0);
        }
    }
}
